package com.hdoit.apollo.web.shop.apis;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.hdoit.apollo.logical.shop.model.Shop;
import com.hdoit.apollo.logical.shop.model.Staff;
import com.hdoit.apollo.logical.shop.service.IStaffService;
import com.hdoit.apollo.logical.viewmodel.shop.StaffSearch;
import com.tennetcn.authority.common.message.AuthorityLoginUser;
import com.tennetcn.authority.component.annotation.ApiAuthPassport;
import com.tennetcn.authority.component.webapi.BaseApi;
import com.tennetcn.authority.component.webapi.ResponseModel;
import com.tennetcn.authority.component.webapi.ResponseStatus;
import com.tennetcn.authority.logical.model.LoginAuthority;
import com.tennetcn.authority.logical.model.LoginUser;
import com.tennetcn.authority.logical.model.Role;
import com.tennetcn.authority.logical.service.ILoginAuthorityService;
import com.tennetcn.authority.logical.service.ILoginUserService;
import com.tennetcn.authority.logical.service.IRoleService;
import com.tennetcn.authority.viewmodel.RoleSearch;
import com.tennetcn.core.common.enums.pub.YesOrNoInteger;
import com.tennetcn.core.common.message.ManageContainer;
import com.tennetcn.core.common.message.ReturnModel;
import com.tennetcn.core.common.utils.CommonUtils;
import com.tennetcn.core.common.utils.DateUtils;
import com.tennetcn.core.common.utils.JsonUtils;
import com.tennetcn.data.enums.ModelStatus;
import com.tennetcn.data.message.PagerModel;

@RestController
@RequestMapping(value = "/api/v1/staff/",method = { RequestMethod.GET,RequestMethod.POST},produces = "application/json;charset=UTF-8")
@CrossOrigin(origins = "*", maxAge = 3600)
@Api(value="/api/v1/staff")
public class StaffApi extends BaseApi{
	@Autowired
	protected ILoginUserService loginUserService;
	
	@Autowired
	protected ILoginAuthorityService loginAuthorityService;
	
	@Autowired
	private IStaffService staffService;
	
	@Autowired
	private IRoleService roleService;
	
	private final String loginTestApi="loginTest";
	private final String registerViewName="register";
	private final String getStaffsByScroll="getStaffsByScroll";
	private final String getRoles="getRoles";
	private final String saveStaff="saveStaff";
	private final String checkAccount="checkAccount";
	private final String getStaffsListForSearchApi="getStaffsListForSearch";
	
	@ApiAuthPassport
    @RequestMapping(value = loginTestApi)
    @ApiOperation(notes = loginTestApi, httpMethod = "POST", value = "登录")
    public String loginTest(String username,String password){
		return logining(username,password,CommonUtils.getKeyId(),"内部测试");
    }
	
	private String logining(String username,String password,String deviceId,String deviceName){
		ResponseModel rm=new ResponseModel();
		LoginUser loginUser=loginUserService.login(username, password);
		if(loginUser==null){
			rm.setStatus(ResponseStatus.dataError);
			rm.setMessage("用户名或密码错误");
		}else{
			LoginAuthority loginAuthority=loginAuthorityService.saveLoginAuthority(loginUser.getId(), loginUser.getName(), deviceId, deviceName);
			List<Role> roles = roleService.queryList(loginUser.getId());
			Staff staff=staffService.queryModel(loginUser.getId());
			if(staff!=null) {
				if(staff.getDeleteMark()==0){
					rm.setStatus(ResponseStatus.dataError);
					rm.setMessage("该员工已删除");
					return rm.toJson();
				}
			}
			if(loginAuthority==null){
				rm.setStatus(ResponseStatus.dataError);
				rm.setMessage("授权出现异常,请与管理员联系");
			}else{
				rm.setStatus(ResponseStatus.success);
				rm.put("userId", loginUser.getId());
				rm.put("username", loginUser.getName());
				rm.put("account", username);
				rm.put("signCode", loginAuthority.getSignCode());
				rm.put("expire", loginAuthority.getExpireDate());
				rm.put("shopId", staff.getShopId());
				rm.put("roles", roles);
			}
		}
		return rm.toJson();
	}

	@ApiAuthPassport
	@RequestMapping(value = registerViewName, method = { RequestMethod.POST })
	@ApiOperation(notes = registerViewName, httpMethod = "POST", value = "注册账号")
	public String register(Model model,String account,String name,String password,String roleMark,Shop shop) {
		ReturnModel rm=loginUserService.checkAccountRule(account);
		ResponseModel responseModel=new ResponseModel();
		
		if(!ManageContainer.SUCCESS.equals(rm.getStatus())) {
			responseModel.setStatus(ResponseStatus.dataError);
			responseModel.setMessage(rm.getMessage());
		}else if(loginUserService.checkAccount(null, account)){
			responseModel.setStatus(ResponseStatus.dataError);
			responseModel.setMessage("已经存在相同账号了");
		}else {
			if(StringUtils.isEmpty(roleMark)) {
				roleMark="boss";
			}
			shop.setCreateDate(DateUtils.getCurrent());
			shop.setDeleteMark(YesOrNoInteger.no);
			shop.setModelStatus(ModelStatus.add);
            
			//进行注册调用
			AuthorityLoginUser authorityLoginUser=new AuthorityLoginUser();
			authorityLoginUser.setId(CommonUtils.getKeyId());
			authorityLoginUser.setAccount(account);
			authorityLoginUser.setName(name);
			authorityLoginUser.setPassword(password);
			authorityLoginUser.setRoleMark(roleMark);
			authorityLoginUser.setCreateDate(DateUtils.getCurrent());
			authorityLoginUser.setModelStatus(ModelStatus.add);
			
			staffService.applyStaff(shop,authorityLoginUser);
		}
		
		return responseModel.toJson();
	}
	
 	@RequestMapping(value = getStaffsByScroll)
    @ApiOperation(notes = getStaffsByScroll, httpMethod = "POST", value = "滚动查找员工信息列表")
    public @ResponseBody String getStaffsByScroll(StaffSearch search,int dataPosition,int pageSize){
    	ResponseModel rm=new ResponseModel();
    	PagerModel pagerModel=null;
    	if(pageSize!=0){
    		int pageindex = (dataPosition%pageSize==0?dataPosition/pageSize:dataPosition/pageSize+1)+1;
    		pagerModel = new PagerModel(pageSize, pageindex);
    	}else{
    		pagerModel=new PagerModel();
    	}

    	List<Staff> staffs=staffService.queryListMP(search, pagerModel);
    	for( Staff staff:staffs){
    		staff.setRoles(roleService.queryList(staff.getId()));
    	}
    	rm.put("staffs",staffs);
    	return rm.toJson();
    }
 	
 	@RequestMapping(value = getRoles)
    @ApiOperation(notes = getRoles, httpMethod = "POST", value = "获取角色信息列表")
    public @ResponseBody String getRoles(RoleSearch search){
    	ResponseModel rm=new ResponseModel();
    	List<Role> roles = roleService.queryList(search, null);
    	
    	rm.put("roles",roles);
    	return rm.toJson();
    }
 	
    @RequestMapping(value = saveStaff)
    @ApiOperation(notes = saveStaff, httpMethod = "POST", value = "保存员工信息")
    public @ResponseBody String saveStaff(Staff staff,String rolesJson,String password){
    	Staff staffPan = staffService.queryModel(staff.getId());
    	ReturnModel rm=loginUserService.checkAccountRule(staff.getMobile());
    	ResponseModel responseModel=new ResponseModel();
    	if(staff.getDeleteMark()==0) {
    		staffPan.setDeleteMark(YesOrNoInteger.yes);
    		staffPan.setModelStatus(ModelStatus.update);
    		if(!staffService.applyChange(staffPan)){
	    		responseModel.setStatus(ResponseStatus.dataError);
	    	}
    		return responseModel.toJson();
    	}
    	
    	if(staffPan==null){
    		staff.setCreateDate(DateUtils.getCurrent());
    		staff.setCreateUserId(getLoginId());
    		staff.setCreateUserName(getLoginName());
    		staff.setDeleteMark(YesOrNoInteger.no);
    		staff.setModelStatus(ModelStatus.add);
    		
    		if(!ManageContainer.SUCCESS.equals(rm.getStatus())) {
    			responseModel.setStatus(ResponseStatus.dataError);
    			responseModel.setMessage(rm.getMessage());
    			return responseModel.toJson();
    		}else if(loginUserService.checkAccount(null, staff.getMobile())){
    			responseModel.setStatus(ResponseStatus.dataError);
    			responseModel.setMessage("已经存在相同账号了");
    			return responseModel.toJson();
    		}
    	}else{
    		staff.setModifyUserId(getLoginId());
    		staff.setModifyUserName(getLoginName());
    		staff.setModifyDate(DateUtils.getCurrent());
    		staff.setModelStatus(ModelStatus.update);
    		
    		if(!ManageContainer.SUCCESS.equals(rm.getStatus())) {
    			responseModel.setStatus(ResponseStatus.dataError);
    			responseModel.setMessage(rm.getMessage());
    			return responseModel.toJson();
    		}else if(loginUserService.checkAccount(staffPan.getId(), staff.getMobile())){
    			responseModel.setStatus(ResponseStatus.dataError);
    			responseModel.setMessage("已经存在相同账号了");
    			return responseModel.toJson();
    		}
    	}
    	
    	@SuppressWarnings("unchecked")
		List<Role> roles = (List<Role>) JsonUtils.readValues(rolesJson, List.class, Role.class);
    	
    	if(!staffService.applyChange(staff,roles,password)){
    		responseModel.setStatus(ResponseStatus.dataError);
    	}
		
    	return responseModel.toJson();
    }
    
    @ApiAuthPassport
	@RequestMapping(value = checkAccount)
	@ApiOperation(notes = checkAccount, httpMethod = "POST", value = "检测账号信息")
	public @ResponseBody String checkAccount(String account){
    	ReturnModel rm=loginUserService.checkAccountRule(account);
		ResponseModel responseModel=new ResponseModel();
		
		if(!ManageContainer.SUCCESS.equals(rm.getStatus())) {
			responseModel.setStatus(ResponseStatus.dataError);
			responseModel.setMessage(rm.getMessage());
		}else if(loginUserService.checkAccount(null, account)){
			responseModel.setStatus(ResponseStatus.dataError);
			responseModel.setMessage("已经存在相同账号了");
			return responseModel.toJson();
		}
		return responseModel.toJson();
	}
    
 	@RequestMapping(value = getStaffsListForSearchApi)
    @ApiOperation(notes = getStaffsListForSearchApi, httpMethod = "POST", value = "员工列表")
    public @ResponseBody String getStaffsListForSearch(StaffSearch search){
    	ResponseModel rm=new ResponseModel();

    	List<Staff> staffs=staffService.queryListMP(search, null);
    	for( Staff staff:staffs){
    		staff.setRoles(roleService.queryList(staff.getId()));
    	}
    	rm.put("staffs",staffs);
    	return rm.toJson();
    }
}
